package com.ship.util;



import com.ship.entity.dto.JsonResult;
import com.ship.entity.dto.ResultCode;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by Luoqb on 2017/5/15.
 */
public class ValidationUtils {

    private static Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> JsonResult validateEntity(T obj){
        JsonResult result = null;
        Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
        if( set!=null&&set.size()>0 ){
            result = new JsonResult();
            result.setResult(ResultCode.PARAMS_ERROR);
            List errorMsg = new ArrayList<>();
            for(ConstraintViolation<T> cv : set){
                errorMsg.add(cv.getMessage());
                break;
            }
            result.setMessage(errorMsg.get(0).toString());
        }
        return result;
    }

    public static <T> JsonResult validateProperty(T obj,String propertyName){
        JsonResult result = null;
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj,propertyName,Default.class);
        if( set!=null&&set.size()>0 ){
            result = new JsonResult();
            result.setResult(ResultCode.PARAMS_ERROR);
            List errorMsg = new ArrayList<>();
            for(ConstraintViolation<T> cv : set){
                errorMsg.add(cv.getMessage());
                break;
            }
            result.setMessage(errorMsg.get(0).toString());
        }
        return result;
    }
}
